package com.itheima.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImp extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        // 1.条件查询分类套餐 创建
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 2.查询前端传过来要删除的id 与菜品类别的id查询，如果查询到了，该菜品类别不能删除，并且抛出异常
        lambdaQueryWrapper.eq(Dish::getCategoryId, id);
        // 3.统计两者相等的数量
         int count = dishService.count(lambdaQueryWrapper);
         //4.如果count大于0 抛出自定义异常
         if(count>0){
             throw  new CustomException("此菜品分类已关联菜品，无法删除！");   // 如果执行到这，后面都不执行

         }

         //查询精品套餐表
         LambdaQueryWrapper<Setmeal> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
         lambdaQueryWrapper1.eq(Setmeal::getCategoryId,id);
         int count1 = setmealService.count(lambdaQueryWrapper1);
        if(count1>0){
            throw  new CustomException("此菜品分类已关联菜品，无法删除！");
        }

        //如果上面的条件都不符合，执行父类的删除语句
        super.removeById(id);


    }
}
